package com.yugao.fintech.antelope.system.manager;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yugao.fintech.antelope.system.constants.SysErrorEnum;
import com.yugao.fintech.antelope.system.mapper.SysTenantMapper;
import com.yugao.fintech.antelope.system.model.entity.SysTenant;
import com.yugao.fintech.framework.assistant.utils.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;


@Slf4j
@Component
public class SysTenantManager extends ServiceImpl<SysTenantMapper, SysTenant> {

    public void validSaveTenantDomain(String domain) {
        LambdaQueryWrapper<SysTenant> lqw = SysTenant.lqw().eq(SysTenant::getDomain, domain);
        if (this.count(lqw) > 0) {
            throw new BizException(SysErrorEnum.TENANT_DOMAIN_EXIST);
        }
    }

    public void validUpdateTenantDomain(Long id, String domain) {
        LambdaQueryWrapper<SysTenant> lqw = SysTenant.lqw().ne(SysTenant::getId, id).eq(SysTenant::getDomain, domain);
        if (this.count(lqw) > 0) {
            throw new BizException(SysErrorEnum.TENANT_DOMAIN_EXIST);
        }
    }

    public long countByPackageId(Long packageId) {
        LambdaQueryWrapper<SysTenant> lqw = SysTenant.lqw().eq(SysTenant::getPackageId, packageId);
        return this.count(lqw);
    }

    public List<SysTenant> listByPackageId(Long packageId) {
        LambdaQueryWrapper<SysTenant> lqw = SysTenant.lqw().eq(SysTenant::getPackageId, packageId);
        return this.list(lqw);
    }

    public List<SysTenant> listSubTenant(Long mainTenantId) {
        LambdaQueryWrapper<SysTenant> lqw = SysTenant.lqw().eq(SysTenant::getMainTenantId, mainTenantId)
                .ne(SysTenant::getId, mainTenantId);
        return this.list(lqw);
    }

    public void updateSubTenantPackageId(Long mainTenantId, Long subPackageId) {
        LambdaUpdateWrapper<SysTenant> lqw = SysTenant.luw().eq(SysTenant::getMainTenantId, mainTenantId)
                .ne(SysTenant::getId, mainTenantId).set(SysTenant::getPackageId, subPackageId);
        this.update(lqw);
    }

}
